package net.sytes.hamir.gamesrequester;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;




public class ArchiveRequester {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//https://secure.chess.com/login?c1=hamir.br@gmail.com&loginpassword=renata66

		try {
			CookieStore cookieStore = new BasicCookieStore();
			HttpContext httpContext = new BasicHttpContext();
			HttpClient httpclient = new DefaultHttpClient();
			httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
			
			//Login
			HttpPost post = new HttpPost("https://secure.chess.com/login");
		    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		    nameValuePairs.add(new BasicNameValuePair("loginusername", "hamir.br@gmail.com"));
		    nameValuePairs.add(new BasicNameValuePair("loginpassword", "renata66"));
		    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			doRequest(post, httpclient, httpContext);

			HttpGet get = new HttpGet("http://www.chess.com/home");
			System.out.println(doRequest(get, httpclient, httpContext));
			
			post = new HttpPost("http://www.chess.com/home/game_archive?sortby=&show=live&member=MarcoSalvo#");
			//post.addHeader("Cookie", "PHPSESSID=a1u7oeq6ellgggs97resu9f890");
			nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("gamearchivecheckbox507824156", "on"));
			nameValuePairs.add(new BasicNameValuePair("Qform__FormControl", "c21"));
			nameValuePairs.add(new BasicNameValuePair("Qform__FormEvent", "QClickEvent"));
			nameValuePairs.add(new BasicNameValuePair("Qform__FormCallType", "Server"));
			nameValuePairs.add(new BasicNameValuePair("Qform__FormCheckableControls","gamearchivecheckbox507824156+gamearchivecheckbox507817571+gamearchivecheckbox507817131+gamearchivecheckbox507810311+gamearchivecheckbox507799042+gamearchivecheckbox507793580+gamearchivecheckbox507783769+gamearchivecheckbox507781101+gamearchivecheckbox507775287+gamearchivecheckbox507246108+gamearchivecheckbox507238290+gamearchivecheckbox507234560+gamearchivecheckbox507222597+gamearchivecheckbox507212332+gamearchivecheckbox507209988+gamearchivecheckbox507202804+gamearchivecheckbox507195784+gamearchivecheckbox507065425+gamearchivecheckbox507060743+gamearchivecheckbox507054889+gamearchivecheckbox506021860+gamearchivecheckbox506019982+gamearchivecheckbox506017436+gamearchivecheckbox506012947+gamearchivecheckbox505703914+gamearchivecheckbox505700063+gamearchivecheckbox505414292+gamearchivecheckbox505412902+gamearchivecheckbox505407837+gamearchivecheckbox505407614+gamearchivecheckbox505403762+gamearchivecheckbox505399832+gamearchivecheckbox505397003+gamearchivecheckbox505392424+gamearchivecheckbox505390048+gamearchivecheckbox505382211+gamearchivecheckbox505204537+gamearchivecheckbox505199707+gamearchivecheckbox505194475+gamearchivecheckbox505192388+gamearchivecheckbox505078946+gamearchivecheckbox505073249+gamearchivecheckbox505071593+gamearchivecheckbox503290289+gamearchivecheckbox503286851+gamearchivecheckbox503279349+gamearchivecheckbox502465447+gamearchivecheckbox502461928+gamearchivecheckbox502457245+gamearchivecheckbox502447335"));
			nameValuePairs.add(new BasicNameValuePair("Qform__FormState", "e4232e2eb4d96c330327ff653a9fc47d"));
			nameValuePairs.add(new BasicNameValuePair("Qform__FormId", "GameArchiveForm"));
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			doRequest(post, httpclient, httpContext);

			/*for(String member:new String [] {"carlosmagdy"}){//,"wendel76","UlissesChess","MarcoSalvo","Heinson","charlestf"}){
				Map<String, String> games = new HashMap<String, String>();
				Collection<String> pages = new ArrayList<String>();
				HttpGet get = new HttpGet("http://www.chess.com/home/game_archive?sortby=&show=live&member=carlosmagdy&page=");
				processPage(doRequest(get, httpclient, httpContext), games, pages);
				for(String page:pages){
					get = new HttpGet("http://www.chess.com/home/game_archive?sortby=&show=live&member="+member+"&page="+page);
					processPage(doRequest(get, httpclient, httpContext), games, null);
				}
				
				post = new HttpPost("http://www.chess.com/home/game_archive?sortby=&show=live&member=carlosmagdy&page=");
				nameValuePairs = new ArrayList<NameValuePair>();
				nameValuePairs.add(new BasicNameValuePair("q", " "));
				nameValuePairs.add(new BasicNameValuePair("c27", " "));
				nameValuePairs.add(new BasicNameValuePair("c25", "1"));
				for(String game:games.keySet()){
					nameValuePairs.add(new BasicNameValuePair("gamearchivecheckbox"+game, "on"));
				}
				nameValuePairs.add(new BasicNameValuePair("Qform__FormControl", "c22"));
				nameValuePairs.add(new BasicNameValuePair("Qform__FormEvent", "QClickEvent"));
				nameValuePairs.add(new BasicNameValuePair("Qform__FormParameter", " "));
				nameValuePairs.add(new BasicNameValuePair("Qform__FormCallType", "Server"));
				nameValuePairs.add(new BasicNameValuePair("Qform__FormUpdates", " "));
				nameValuePairs.add(new BasicNameValuePair("Qform__FormId", "GameArchiveForm"));

				post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				doRequest(post, httpclient, httpContext);
			}*/
			
						
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	private static void processPage(String source, Map<String, String> games, Collection<String> pages){
		Pattern p = Pattern.compile("<a href=\"/home/game_archive.*?page=([^\"]+)");
		Matcher m = p.matcher(source);
		
		if(pages !=null){
			Map<String, String> pagesMap = new TreeMap<String, String>();
			while(m.find()){
				pagesMap.put(m.group(1), null);
			}
		
			pages.addAll(pagesMap.keySet());
		}
		
		p = Pattern.compile("gamearchivecheckbox(\\d+)");
		m = p.matcher(source);
		while(m.find()){
			games.put(m.group(1), null);
		}
	}
	
	private static String doRequest(HttpUriRequest req, HttpClient client, HttpContext httpContext) throws Exception{
		HttpResponse response = client.execute(req, httpContext);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		String line = "";
		StringBuffer buf = new StringBuffer();
		while ((line = rd.readLine()) != null) {
			if(line.indexOf("PGN") > -1){
				System.out.println(line);
			}
			buf.append(line);
		}
		return buf.toString();
	}

}
